<template>
  <div class="DeviceDet">
    <div class="Herd_Color"></div>
    <div class="Herd_Title">新增设备</div>
    <div class="Gou_Chyts">
      <el-button type="info" onclick="window.history.go(-1)" icon="el-icon-back">返回</el-button>
    </div>
    <!-- ====================================================================== -->
    <!--  ========================基本信息======================== -->
    <!--Id	int	Unchecked
    CreateOn	datetime	Unchecked
    UpdateOn	datetime	Unchecked
    Repair_times	int	Unchecked
    maintain_cycle	nvarchar(50)	Checked
    Shouming	nvarchar(255)	Checked
    picture	nvarchar(255)	Checked
    BaoFei_SH	nvarchar(50)	Checked
    Tingyong_desc	nvarchar(500)	Checked-->
    <!-- ====================================================================== -->
    <div class="OveRa_LayOPut">
      <div class="Herd_BackGrd_JiBen">
        <div class="Herd_Tow_Title">基本信息</div>
        <br />
        <p class="Purchase_Division"></p>
        <br />
        <el-form :model="DataDb" :inline="true" label-width="100px">
          <el-form-item label="设备型号"><el-input v-model="DataDb.xinghao" style="width: 200px;"></el-input></el-form-item>
          <el-form-item label="设备名称"><el-input v-model="DataDb.name"  style="width: 200px;"></el-input></el-form-item>
          <el-form-item label="本厂编号"><el-input v-model="DataDb.Eq_number_local"  style="width: 200px;"></el-input></el-form-item>
          <el-form-item label="出厂编号"><el-input v-model="DataDb.Eq_number_chuchang"  style="width: 200px;"></el-input></el-form-item>

          <el-form-item label="使用部门">
            <el-select
              v-model="DataDb.Use_depart"
              value-key="Id"
              placeholder="请选择" style="width: 200px;"@change="getsel">
              <el-option
                v-for="item in deplist"
                :label="item.name"
                :key="item.Id"
                :value="item.Id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备状态" >
            <el-select v-model="DataDb.status" placeholder="请选择"style="width: 200px;">
              <el-option v-for="item in statuslist" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下次保养日期"><el-date-picker style="width: 200px;" v-model="DataDb.maintain_next" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder readonly></el-date-picker></el-form-item>
          <el-form-item label="产地"><el-input v-model="DataDb.Eq_chandi" style="width: 200px;" clearable></el-input></el-form-item>
          <el-form-item label="功率"><el-input v-model="DataDb.Eq_gonglv" style="width: 200px;"></el-input></el-form-item>
          <el-form-item label="规格"><el-input v-model="DataDb.Eq_guige" style="width: 200px;"></el-input></el-form-item>
          <el-form-item label="备注"><el-input v-model="DataDb.Eq_remark" style="width: 200px;"></el-input></el-form-item>
          <el-form-item label="设备类别">
            <el-select
              v-model="DataDb.cateid"
              value-key="Id"
              @change="getCateId($event)"
              placeholder="请选择" style="width: 200px;">
              <el-option
                v-for="item in catelist"
                :key="item.value"
                :label="item.name"
                :value="item.Id"></el-option>
            </el-select>
            <el-button type="primary" @click="showCateDialog" size="small">类别管理</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- =================================================== -->
      <!-- ============ 设备信息 ============== -->
      <!-- =================================================== -->
      <div class="Herd_BackGrd_Second">
        <div class="Herd_Tow_Title">设备信息</div>
        <br />
        <p class="Purchase_Division"></p>
        <br />
        <el-form :model="DataDb" :inline="true" label-width="100px">
          <el-form-item label="出厂日期"><el-date-picker v-model="DataDb.ManufactureOn" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" style="width: 200px;" ></el-date-picker></el-form-item>
          <el-form-item label="购置日期"><el-date-picker v-model="DataDb.BuyOn" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 200px;"></el-date-picker></el-form-item>
          <el-form-item label="保养周期">
            <el-input v-model="DataDb.maintain_cycle" @input="ValidateInt('maintain_cycle',DataDb)" style="width: 182px;"></el-input> 天
            <!--<div class="block">
              <el-date-picker
                v-model="DataDb"
                type="week"
                format="yyyy 第 WW 周"
                placeholder="选择周"
                style="width: 88%;"></el-date-picker>
            </div>-->
          </el-form-item>
          <el-form-item label="设备寿命"><el-input v-model="DataDb.Shouming" style="width: 200px;"></el-input></el-form-item>
        </el-form>
        <div class="Block_Phto">
          <div style="padding: 20px 20px 10px">设备图片</div>
          <div style="margin: 0px 20px 10px;width: 200px;height: 200px;">
            <el-upload
              class="avatar-uploader"
              action="/apis/ComApi.asmx/UpImg"
              :show-file-list="false"
              :on-success="function(res, file){return handleAvatarSuccess(res, file,'picture',DataDb)}"
              :on-change="function(file) {return imgPreview(file,'picture_full',DataDb)}">
              <img v-if="DataDb.picture_full" :src="DataDb.picture_full" style="max-width: 200px;max-height: 200px;" />
              <i v-else class="el-icon-plus avatar-uploader-icon" style="width: 200px;height:200px;"></i>
            </el-upload>
          </div>
        </div>
      </div>
      <!-- =================================================== -->
      <!-- ============ 维保记录 ============== -->
      <!-- =================================================== -->
      <div class="Herd_BackGrd_Level">
        <div class="Herd_Tow_Title_weibaoH">
          <span>维保记录</span>
          <el-button type="primary" @click="weibaoOper('',true)" size="small" v-if="canedit==true">新增维保</el-button>
        </div>
        <br />
        <p class="Purchase_Division"></p>
        <el-table
          :data="weibaolog"
          style="width: 95%;background-color:#fff;margin-left: 10px;"
          :height="420"
          :max-height="420"
          stripe>
          <el-table-column type="index" label="序号" align="center" width="60px;"></el-table-column>
          <el-table-column prop="a" label="维修类别" align="center">
            <template slot-scope="scope">
              <el-select
                clearable
                filterable
                allow-create
                v-model="scope.row.RepairCate"
                value-key="value"
                placeholder="请选择">
                <el-option v-for="item in WeibaoCateList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="b" label="维修内容" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.RepairNeirong"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="c" label="维修日期" align="center">
            <template slot-scope="scope">
              <div class="block">
                <el-date-picker
                  v-model="scope.row.RepairOn"
                  type="date"
                  placeholder="选择日期"
                  style="width: 90%"
                ></el-date-picker>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="d" label="维保凭证" align="center" >
            <template slot-scope="scope" style="display: flex;align-items: center">
              <div style="display: flex;align-items: center;justify-content: center;" v-if="scope.$index>Repair_times-1">
                <el-upload
                  class="avatar-uploader" style="width: 50px;height: 50px;display: inline-block;margin-right:10px;"
                  action="/apis/ComApi.asmx/UpImg"
                  :show-file-list="false"
                  :on-success="function(res, file){return handleAvatarSuccess(res, file,'RepairImg',scope.row)}"
                  :on-change="function(file) {return imgPreview(file,'RepairImg_full',scope.row)}">
                  <img v-if="scope.row.RepairImg_full" :src="scope.row.RepairImg_full" style="max-width: 50px;max-height: 50px;" />
                  <i v-else class="el-icon-plus avatar-uploader-icon" style="width: 50px;height:50px;"></i>
                </el-upload>
                <el-button size="small" type="danger" @click="weibaoOper(scope,false)" icon="el-icon-delete"></el-button>
              </div>
              <div style="display: flex;align-items: center;justify-content: center;" v-else>
                <el-popover placement="right" trigger="hover" v-if="scope.$index<=Repair_times-1">
                  <el-image slot="reference" :src="scope.row.RepairImg_full" :alt="scope.row.RepairImg_full" style="max-height: 50px;max-width: 50px;margin-right:10px;"></el-image>
                  <el-image :src="scope.row.RepairImg_full"></el-image>
                </el-popover>
                <el-button size="small" type="danger" @click="weibaoOper(scope,false)" icon="el-icon-delete" style="visibility: hidden" v-if="scope.$index<=Repair_times-1"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="Botm_PtnRpo">
      <el-button type="primary" @click="saveData" v-if="canedit==true" >确认</el-button>
      <el-button class="bm_btn" onclick="window.history.go(-1)" type="info">返回</el-button>
    </div>
    <el-dialog
      title="类别管理"
      append-to-body
      :visible.sync="CateDialog"
      width="420px" center>
      <el-table :data="catelist" height="300" style="text-align: center">
        <el-table-column width="140" label="名称">
          <template slot-scope="scope">
            <el-input style="width: 100%;" v-model="scope.row.name"></el-input>
          </template>
        </el-table-column>
        <el-table-column width="140" label="排序">
          <template slot-scope="scope">
            <el-input style="width: 100%;" v-model="scope.row.orderby" @input="ValidateInt('orderby',scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column width="90" label="操作">
          <template slot-scope="scope">
            <el-button @click="saveCate(scope.row)" type="primary" size="small">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        width="420px" center
        title="新增类别"
        :visible.sync="newCateDialog"
        append-to-body>
        <el-form label-width="80px">
          <el-form-item label="名称" style="width:297px">
            <el-input v-model="newCate.name"></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-select
              v-model="newCate.orderby"
              value-key="Id"
              placeholder="请选择">
              <el-option
                v-for="item in  parseInt(catelist.length+1) "
                :key="item"
                :label="item"
                :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center">
              <el-button @click="newCateDialog = false">取 消</el-button>
              <el-button type="primary" @click="saveCate(newCate)">确 定</el-button>
          </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showNewCateDialog">新 增</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      DataDb:{picture:'',picture_full:''},
      statuslist:["正常","维护中", "待维护","工作中",],
      Repair_times:0,//维保次数
      weibaolog:[{RepairImg_full:"",RepairImg:"",RepairCate:'',RepairNeirong:'',RepairOn:'',CreatedOn:'2020-05-20',}],//维保
      WeibaoCateList:[],//维保类
      deplist:[],//部门
      catelist:[],//类别
      CateDialog:false,
      newCateDialog:false,/*类别新增*/
      newCate:{
        name:"",
        CreateOn:"2020-06-20",
        UpdateOn:"2020-06-20",
        orderby:"",
      },//新增类别
      canedit:true,// 编辑
      lastWeiBao:'',
    };
  },
  created() {
    this.getData(1,{},'catelist');//类别
    this.getData(2,{},'deplist');//部门
    this.getData(3,{},'WeibaoCateList');//维保类别
    this.canedit=(this.$route.query.edit||null)==null;
    let id=this.$route.query.id||null
    if(id!=null){
      this.getData_Detail(4,{id:id})
    }else{
      this.lastWeiBao=this.DateGeshi_Date(Date.now(),'yyyy-MM-dd')
    }
  },
  methods: {
    getsel(e){
      console.log(e,this.DataDb.Use_depart,9999)
    },
    /*#region 维保*/
    weibaoOper(e,flag) {
      if (flag==true){
        this.weibaolog.push({RepairImg_full:"",RepairImg:"",RepairCate:'',RepairNeirong:'',RepairOn:'',CreatedOn:'2020-05-20'});
      }else{
        this.weibaolog.splice(e.$index, 1);
      }
    },
    /*#endregion*/
    /*#region 类别管理*/
    saveCate(e){
      let that=this;
      let isnew=false;
      if (e.name==''){that.$message.error("名称不能为空");return;}
      if(e.orderby==""){e.orderby=0}
      if (e.Id==0){isnew=true;}
      e.CreateOn='2020-06-20';e.UpdateOn='2020-06-20';
      e.userId=localStorage.getItem("message").Id,
      axios("/apis/ScDeviceManage.asmx/saveData?index=2&jsondata=" + JSON.stringify(e)).then(({ data }) => {
        var datas = that.$x2js.xml2js(data);
        let result=JSON.parse(datas.string.__text);
        that.$message({type:result.type,message:result.message});
        if(result.type=='success'){
          if (isnew==true){that.newCateDialog=false;}
          this.getData(1,{},'catelist')
        }
      });
    },//类别保存
    showCateDialog(){this.CateDialog=true;},
    showNewCateDialog(){
      this.newCateDialog = true
      this.newCate={
        Id:0,
        name:"",
        CreateOn:"2020-06-20",
        UpdateOn:"2020-06-20",
        orderby:"",
      };
    },
    /*#endregion*/
    /*#region 图片操作*/
    imgPreview(file,name,object) {
      let fileName = file.name;
      let regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
      if (regex.test(fileName.toLowerCase())) {
        object[name]=URL.createObjectURL(file.raw)
      } else {
        this.$message.error('请选择图片文件');
      }
    },
    handleAvatarSuccess(res, file,name,object) {
      var datas = this.$x2js.xml2js(res);
      object[name]=datas.UpFileReturn.url;
    },
    /*#endregion*/
    saveData(){
      let log=[];
      for (let i = 0; i <this.weibaolog.length ; i++) {
        if (this.weibaolog[i].RepairOn!=''){log.push(this.weibaolog[i])}
      }
      let jsondata={
        userId:0,
        sbdet:this.DataDb,
        loglist:log,
      };
      let jsondata_str=JSON.stringify(jsondata)
      console.log(jsondata_str,66666)
      axios.post("/apis/ScDeviceManage.asmx/saveData", { index: 1, jsondata: jsondata_str }).then(({ data }) => {
        let result=JSON.parse(data.d)
        this.$message({type:result.type,message:result.message});
        if (result.type == "success") {window.history.go(-1);}
      });
    },
    getCateId(e){this.DataDb.cateid=e},
    getData_Detail(index,jsondata){
      let jsondata_str=JSON.stringify(jsondata)
      axios("/apis/ScDeviceManage.asmx/getData?index=" + index + "&jsondata=" + jsondata_str).then(({ data }) => {
        var datas = this.$x2js.xml2js(data);
       let result=JSON.parse(datas.string.__text);
        this.DataDb=result.baseobj
        this.weibaolog=result.log
        this.Repair_times=result.log.length
        if (this.DataDb.maintain_next==''){
          this.lastWeiBao=this.DateGeshi_Date(Date.now(),'yyyy-MM-dd')
        }else{
          this.lastWeiBao=this.addDays(new Date(this.DataDb.maintain_next),0 - parseInt(this.DataDb.maintain_cycle))
        }
        console.log(this.lastWeiBao,'上传')
      });
    },
    getData(index,jsondata,result){
      let jsondata_str=JSON.stringify(jsondata)
      axios("/apis/ScDeviceManage.asmx/getData?index=" + index + "&jsondata=" + jsondata_str).then(({ data }) => {
        var datas = this.$x2js.xml2js(data);
        console.log(datas,33333)
        this[result]=JSON.parse(datas.string.__text);
        console.log(result,this[result],999999)
      });
    },
    ValidateInt(name,object){
      object[name]=object[name].replace(/[^\d]/g,'');
      if (name=='maintain_cycle'&&object[name]!=''){
        this.DataDb.maintain_next=this.addDays(this.lastWeiBao,parseInt(object[name]))
      }else if (name=='maintain_cycle'&&object[name]==''){
        this.DataDb.maintain_next='';
      }
    },
  }
};
</script>
<style  lang="scss" scoped>
@import "@/assets/scss/base.scss";
.DeviceDet .avatar-uploader,.DeviceDet .avatar-uploader-icon {display: flex;align-items: center;justify-content: center;height:100% ;width: 100%;}
.DeviceDet .avatar-uploader{border: 1px dashed #cccccc;}
.DeviceDet .avatar-uploader:hover{border-color: #3a8ee6}
.Herd_Color {
  margin-top: 20px;
  margin-left: 20px;
  height: 20px;
  width: 5px;
  background-color: rgb(36, 15, 230);
}
.Herd_Title {
  margin-top: -20px;
  margin-left: 30px;
}
.Gou_Chyts {
  margin-left: 92%;
  margin-top: -30px;
}
/* 总体高度 */
.OveRa_LayOPut {
  height: 780px;
  overflow-x: hidden;
}
/* 基本信息渲染 */
.Herd_BackGrd_JiBen {
  width: 98%;
  background-color: white;
  margin-top: 30px;
  margin-left: 15px;
  border-radius: 8px;
}
.Herd_Tow_Title{
  font-size: $font-size-medium;
  font-weight: bold;
  padding-top: 10px;
  margin-left: 20px;
}
.Herd_Tow_Title_weibaoH {
  font-size: $font-size-medium;
  font-weight: bold;
  padding-top: 10px;
  /*margin-left: 20px;*/
  margin: 0 20px;
  display: flex;align-items: center;justify-content: space-between;
}
.Purchase_Division {
  border: 0.5px solid $linecolor;
  width: 97%;
  margin-left: 10px;
}
//设备信息
.Herd_BackGrd_Second {
  float: left;
  margin-top: 20px;
  height: 480px;
  width: 48%;
  background-color: white;
  margin-left: 15px;
  border-radius: 8px;
}
//维保记录
.Herd_BackGrd_Level {
  float: right;
  margin-top: 20px;
  height: 480px;
  width: 49%;
  background-color: white;
  margin-right: 15px;
  border-radius: 8px;
}
//图片大小
.Block_Phto {
  width: 300px;
}

.avatar {
  width: 80px;
  height: 40px;
}
//底部按钮
.Botm_PtnRpo {
  margin-top: 10px;
  text-align: center;
}
</style>
